package stud.mpgame.physics;

import flash.display.Sprite;
import flash.Lib;
import haxe.FastList;
import haxe.FastList;

import stud.mpgame.flash.map.GameMap;

/**
 * ...
 * @author pavel[f.pavel91@gmail.com]
 */
class BroadPhase {

	private var bodies:FastList< Circle >; //circles
	
	private var cells:Array< Array< IBody > >;
	
	private static var cellSize:Int = 64;
	private var width:Int;
	private var height:Int;
	
	public function new(gameMap:GameMap) {
		this.bodies = new FastList < Circle >();
		this.cells = new Array< Array< IBody > >();
		
		this.width = Std.int(gameMap.map.size.width);
		this.height = Std.int(gameMap.map.size.height);
		for (i in 0...height) {
			var temp:Array< IBody > = new Array< IBody >();
			for (j in 0...width) {
				if (gameMap.map.model[i * width + j] == 0) {
					temp.push(null);
				} else if (gameMap.map.model[i * width + j] == 1) {
					temp.push(new AABB(cellSize * j, cellSize * (i + 1), cellSize * (j + 1), cellSize * i));
				} else if (gameMap.map.model[i * width + j] == 2) {
					//temp.push(new Segment(/*cellSize * (i + 1), cellSize * j, new Vector2D(), new Vector2D()*/));
					temp.push(new AABB(cellSize * j, cellSize * (i + 1), cellSize * (j + 1), cellSize * i));
				}
			}
			cells.push(temp);
		}
		/*for (i in 0...height) {
			//var check:String = "";
			for (j in 0...width) {
				if(cells[i][j] != null) {
					//var sprite:Sprite = new Sprite();                
					//sprite.graphics.beginFill(0xaaaaff);
					trace(cellSize * j + " " + cellSize * i + " " + cellSize * (j + 1) + " " +cellSize * (i + 1));
					//sprite.graphics.drawRect(cellSize * j, cellSize * i, cellSize, cellSize);
					//sprite.graphics.endFill();
					//Lib.current.addChild(sprite);
				}
				//check += cells[i][j] == null ? " 0 " : " 1 ";
			}
			//trace(check);
		}*/
	}
	
	public function update() {
		for (body in bodies) {
			var x:Int = body.getCellX();
			var y:Int = body.getCellY();
			for (i in x - 1...x + 2)
				for (j in y - 1...y + 2)
					if (i >= 0 && j >= 0 && j < height && i < width && cells[j][i] !=  null)
						cells[j][i].intersect(body);
		}
	}
	
	public function addCircle(circle:Circle) {
		bodies.add(circle);
	}
	
	public function removeCircle(circle:Circle) {
		bodies.remove(circle);
	}
	
}